<template>
  <div class="app-container">
    <el-card class="box-card">
      <h3>土地内容</h3>
      <el-form ref="dataForm" :rules="rules" :model="lease" label-width="150px">
        <el-form-item label="土地编号" prop="landNo">
          <el-input v-model="lease.landNo" placeholder="请输入土地编号" />
        </el-form-item>
        <el-form-item label="面积(m²)" prop="area">
          <el-input v-model="lease.area" type="number" placeholder="请输入面积" />
        </el-form-item>
        <el-form-item label="配送次数" prop="nums">
          <el-input v-model="lease.nums" type="number" placeholder="请输入配送次数" @keyup.native="provingNum($event)" />
        </el-form-item>
        <el-form-item label="价格(元)" prop="price">
          <el-input v-model="lease.price" type="number" placeholder="请输入价格" @keyup.native="proving($event)" />
        </el-form-item>
        <el-form-item label="所属地皮" prop="leaseId">
          <el-select v-model="lease.leaseId" placeholder="选择所属地皮">
            <el-option v-for="(item, index) in typeList" :key="index" :label="item.title" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="展示图片" prop="imageUrl">
          <el-upload
            :action="uploadPath"
            :headers="headers"
            :on-success="handleimgsUrl"
            :on-error="handleErrorimgsUrl"
            :before-upload="beforeAvatarUpload"
            accept=".jpg, .jpeg, .png, .gif"
            list-type="picture"
            class="upload-img"
          >
            <div v-loading="loading" class="preimg" />
            <div v-show="lease.imageUrl" :style="'background-image:url('+lease.imageUrl+')'" class="preimg" />
            <i class="el-icon-plus" />
            <div slot="tip" class="el-upload__tip">只能上传jpg/jpeg/png/gif文件，且不超过2M</div>
          </el-upload>
          <el-input v-model="lease.imageUrl" type="hidden" class="hidden-input" />
        </el-form-item>
      </el-form>
    </el-card>
    <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button v-if="!lease.id" type="primary" @click="handleCreate">保存内容</el-button>
      <el-button v-if="lease.id" type="primary" @click="handleEdit">更新内容</el-button>
    </div>
  </div>
</template>

<style>
  .hidden-input{
    display: block;
    width:0px;
    height:0px;
  }
  .el-upload--picture{
    position: relative;
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    border-radius: 6px;
    box-sizing: border-box;
    width: 148px;
    height: 148px;
    cursor: pointer;
    line-height: 146px;
    vertical-align: top;
  }
  .el-upload-list--picture{
    display: none;
  }
  .upload-img .preimg{
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
    background-repeat:no-repeat;
    background-size:contain;
    background-position:center;
  }
  .el-loading-spinner{
    top:0;
  }
</style>

<script>
import { editLand, createLand, detailLand } from '@/api/land'
import { selectCategory } from '@/api/lease'
import { uploadPath } from '@/api/storage'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'

export default {
  name: 'LandAdd',
  data() {
    const validateAcquaintance = (rule, value, callback) => {
      // 输入 8--，value 为 8
      // 估计这里内部使用了 parseInt() / parseFloat()
      const newvalue = value.toString()
      if (newvalue.indexOf('.') > -1 && newvalue.split('.')[1].length > 2) {
        callback(new Error('价格最多两位小数'))
      } else {
        callback()
      }
    }
    return {
      leaseId: '',
      uploadPath,
      lease: {
        imageUrl: '', address: ''
      },
      selectedAddr: [],
      typeList: [],
      loading: false,
      rules: {
        landNo: [
          { required: true, message: '土地编号不能为空', trigger: 'blur' }
        ],
        area: [
          { required: true, message: '面积不能为空', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '价格不能为空', trigger: 'blur' },
          { validator: validateAcquaintance, trigger: 'blur' }
        ],
        leaseId: [
          { required: true, message: '所属地皮不能为空', trigger: 'blur' }
        ],
        imageUrl: [
          { required: true, message: '图片不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    headers() {
      return {
        accessToken: getToken()
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    init: function() {
      const leaseId = this.$route.query.id
      if (leaseId) {
        detailLand(leaseId).then(response => {
          this.lease = Object.assign({}, response.data.data)
          this.lease.price = this.lease.price / 100.0
          this.selectedAddr = [this.lease.province, this.lease.city]
        })
      }
      selectCategory()
        .then(response => {
          this.typeList = response.data.data
        })
        .catch(() => {})
    },
    handleCancel: function() {
      this.$router.push({ path: '/home/landlist' })
    },
    handleCreate: function() {
      this.formValidate(1)
    },
    handleEdit: function() {
      this.formValidate(2)
    },
    formValidate: function(type) {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const finalCont = {
            ...this.lease
          }
          finalCont.price = finalCont.price * 100
          if (type === 1) {
            createLand(finalCont)
              .then(response => {
                this.$notify.success({
                  title: '成功',
                  message: '添加成功'
                })
                this.$router.push({ path: '/home/landlist' })
              })
              .catch(response => {
                MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
                  confirmButtonText: '确定',
                  type: 'error'
                })
              })
          } else if (type === 2) {
            editLand(finalCont)
              .then(response => {
                this.$notify.success({
                  title: '成功',
                  message: '添加成功'
                })
                this.$router.push({ path: '/home/landlist' })
              })
              .catch(response => {
                MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
                  confirmButtonText: '确定',
                  type: 'error'
                })
              })
          }
        } else {
          this.$notify.error({
            title: '失败',
            message: '请完善以上表单'
          })
        }
      })
    },
    handleimgsUrl(response, file, fileList) {
      if (response.errno === 200) {
        this.lease.imageUrl = response.url
        this.loading = false
      }
    },
    handleErrorimgsUrl(response, file, fileList) {
      this.$notify.error({
        title: '失败',
        message: '请重新上传图片'
      })
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 / 2 < 2
      this.loading = true
      if (!isLt2M) {
        this.$notify.error({
          title: '失败',
          message: '请重新上传2MB以内的图片'
        })
        this.loading = false
      }
      return isLt2M
    },
    proving(e) {
      const keynum = window.event ? e.keyCode : e.which
      if (keynum === 109 || keynum === 189) {
        e.target.value = ''
        this.lease.price = ''
        this.$notify.error({
          title: '',
          message: '价格最小值为0'
        })
      }
    },
    provingNum(e) {
      const keynum = window.event ? e.keyCode : e.which
      if (keynum === 109 || keynum === 189) {
        e.target.value = ''
        this.lease.nums = ''
        this.$notify.error({
          title: '',
          message: '配送次数不能为负数'
        })
      }
    }

  }
}
</script>
